//
//  YWRollView.m
//  GoFarm-V1.2.0
//
//  Created by David Yu on 30/3/16.
//  Copyright © 2016年 yanwei. All rights reserved.
//

#import "YWRollView.h"
#import "SPProductModel.h"

#define WeakSelf  __weak __typeof(&*self)weakSelf = self;

@interface YWRollView()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView  *collectionView;
@property (nonatomic, strong) UIPageControl     *pageControl;
@property (nonatomic, strong) NSTimer           *timer;
@property (nonatomic, strong) NSMutableArray    *dataSource;

@end

@implementation YWRollView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.isCycleRun = YES;
        self.dataSource = [[NSMutableArray alloc] init];
        
        UICollectionViewFlowLayout *rollLayout = [[UICollectionViewFlowLayout alloc] init];
        rollLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:rollLayout];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.backgroundColor = self.backgroundColor;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.offset(0);
        }];
        
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.backgroundColor = [UIColor clearColor];
        _pageControl.numberOfPages = 0;
        _pageControl.currentPage = 0;
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        _pageControl.hidesForSinglePage = YES;
        _pageControl.pageIndicatorTintColor = RGBCOLOR(200, 200, 200);
        [_pageControl addTarget:self action:@selector(pageChangeAction) forControlEvents:UIControlEventValueChanged];
        [self addSubview:_pageControl];
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
            make.centerX.equalTo(self.mas_centerX);
            make.height.offset(20);
        }];
    }
    
    return self;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = self.newsItems.count?self.dataSource.count:1;
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:cell.bounds];
    iv.backgroundColor = [UIColor whiteColor];
    iv.contentMode = UIViewContentModeScaleAspectFill;
    iv.clipsToBounds = YES;
    iv.image = [UIImage imageNamed:@"banner"];
    [cell.contentView addSubview:iv];
//    UIView *bgView = [[UIView alloc] init];
//    bgView.backgroundColor = [UIColor blackColor];
//    bgView.alpha = 0.3;
//    [cell.contentView addSubview:bgView];
//    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.offset(0);
//        make.height.offset(30);
//    }];
    if (self.newsItems.count) {
        [iv yy_setImageWithURL:[NSURL URLWithString:[self.dataSource[indexPath.row] productIconUrl]] placeholder:[UIImage imageNamed:@"banner"]];

        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.font = [UIFont systemFontOfSize:13];
        titleLabel.text = [self.dataSource[indexPath.row] productName];
        titleLabel.hidden = YES;
        [cell.contentView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(15);
            make.centerY.equalTo(cell.contentView.mas_centerY);
            make.right.offset(-80);
        }];
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.bounds.size.width, self.bounds.size.height);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout  minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count) {
        if (_onClickItemBlock) {
            _onClickItemBlock(indexPath.row);
        }
    }
}

#pragma mark - timer
- (void)actionRun {
    CGFloat x = _collectionView.contentOffset.x + self.bounds.size.width;
    [_collectionView setContentOffset:CGPointMake(x, _collectionView.contentOffset.y) animated:YES];
}

- (void)startRun {
    if (self.dataSource.count>1) {
        [self startTimer];
    }else {
        [_timer invalidate];
    }
}

- (void)startTimer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_timerInterval?:5 target:self selector:@selector(actionRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

#pragma mark - action
- (void)pageChangeAction {
    CGFloat x = (_pageControl.currentPage+1) * self.bounds.size.width;
    [_collectionView setContentOffset:CGPointMake(x, 0) animated:YES];
}

#pragma mark - get set
- (void)setNewsItems:(NSArray *)newsItems {
    _newsItems = newsItems;
    [_dataSource removeAllObjects];
    [_dataSource addObjectsFromArray:newsItems];
    _pageControl.numberOfPages = newsItems.count;
    CGPoint point;
    if (newsItems.count>1) {
        [_dataSource addObject:newsItems.firstObject];
        [_dataSource insertObject:newsItems.lastObject atIndex:0];
        point = CGPointMake(self.bounds.size.width, 0);
    }else {
        point = CGPointMake(0, 0);
    }
    [_collectionView reloadData];
    WeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.collectionView.contentOffset = point;
    });
}

- (void)setIsHavePageVC:(BOOL)isHavePageVC {
    _isHavePageVC = isHavePageVC;
    _pageControl.hidden = !isHavePageVC;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger count = self.newsItems.count;
    if (count==1) {
        return;
    }
    CGFloat x = scrollView.contentOffset.x;
    NSInteger page=0;
    if (x <= 0) {
        if (_isCycleRun) {
            scrollView.contentOffset = CGPointMake(self.bounds.size.width*count, 0);
            page = count-1;
        }
    }else if (x >= self.bounds.size.width*(count+1)) {
        if (_isCycleRun) {
            scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
            page = 0;
        }
    }else {
        page = x / self.bounds.size.width - 1;
    }
    _pageControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_timer invalidate];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (_isCycleRun && self.newsItems.count>1) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_timerInterval?:5 target:self selector:@selector(actionRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }else {
        [_timer invalidate];
    }
}


@end
